package com.omenkk.juc.c3;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.function.IntUnaryOperator;

public class demo2 {
    public static void main(String[] args) {
        AtomicInteger i=new AtomicInteger(0);
        System.out.println(i.incrementAndGet());//++1  //1
        System.out.println(i.getAndIncrement());//i++  //1
        System.out.println(i.getAndAdd(3));//获取并且增加  //2
        System.out.println(i.addAndGet(3));//增加并且获取  //8
        i.updateAndGet(value->value*10);
        //可以采用CAS+重试策略
        System.out.println(i);
        updateAndGet(i,value->value/2);
        System.out.println(i);
        //原子引用
        AtomicReference<BigDecimal> reference=new AtomicReference<>(new BigDecimal("10000"));
        BigDecimal prev = reference.get();

    }

    public static void updateAndGet(AtomicInteger i, IntUnaryOperator operator) {
        while (true) {
            int prev = i.get();
            int next = operator.applyAsInt(prev);
            if (i.compareAndSet(prev, next)) {
                break;
            }
        }

    }
}
